# coding=utf8
__author__ = 'lijian'
from utils import byteUtil
from utils.ftp import MyFTP
import struct
import os
import logging
import setting
import json
import thread
import time
import datetime
from protocol.uplink.packet import *

# ftp升级
def fn_9(dataUnit):
    thread.start_new(upgrade, (dataUnit,))
    return True


def fn_10(dataUnit):
    beforeUpdateInfo = {
        "beforeVersion": "0000",
        "beforeDate": "1970-01-01",
        "upgradeTime": "1970-01-01 0:0:0"
    }

    try:
        f = open(setting.UPGRADE_INFO, 'r')
        txt = f.read()
        if len(txt) > 0:
            beforeUpdateInfo = eval(txt)
        f.close()
    except:
        logging.warn(setting.UPGRADE_INFO + " not exist")

    data = []
    data.extend(byteUtil.strToBytes(beforeUpdateInfo["beforeVersion"], 4))  # 升级前终端软件版本号
    data.extend(byteUtil.encodeDayMonthYear(beforeUpdateInfo["beforeDate"]))  # 升级前终端软件发布日期
    data.extend(byteUtil.strToBytes(setting.termInfo["softwareVersion"], 4))  # 升级后终端软件版本号
    data.extend(byteUtil.encodeDayMonthYear(setting.termInfo["softwareReleaseDate"]))  # 升级前终端软件发布日期
    t = datetime.datetime.strptime(beforeUpdateInfo["upgradeTime"], "%Y-%m-%d %H:%M:%S")
    data.extend(byteUtil.encodeA15(t))  # 升级发生时间

    du = DataUnit(pn=dataUnit.PN, fn=dataUnit.FN, data=data)
    return du


def upgrade(dataUnit):
    data = dataUnit.rawData
    IP = str(data[0]) + "." + str(data[1]) + "." + str(data[2]) + "." + str(data[3])
    port = byteUtil.decodeShort(data[4:6])

    offset = 12
    end = data[offset:].index(0)
    loginName = struct.pack('B' * end, *data[offset:offset + end])
    offset += 10

    end = data[offset:].index(0)
    password = struct.pack('B' * end, *data[offset:offset + end])
    offset += 10

    end = data[offset:].index(0)
    serverPath = struct.pack('B' * end, *data[offset:offset + end])
    offset = offset + 20 + 20

    end = data[offset:].index(0)
    file = struct.pack('B' * end, *data[offset:offset + end])

    if not serverPath.endswith("/"):
        serverPath = serverPath + "/"

    remotePath = serverPath + file
    localPath = "/tmp/upgrade.tar.gz"

    logging.info("ftp upgrade files")

    ftp = MyFTP()
    rtn = ftp.download(IP, port, loginName, password, remotePath, localPath)

    if rtn:
        os.system("chmod 777 /work/pyRTU/upgrade.sh")
        os.system("/work/pyRTU/upgrade.sh")

        info = {
            "beforeVersion": setting.termInfo["softwareVersion"],
            "beforeDate": setting.termInfo["softwareReleaseDate"],
            "upgradeTime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }

        jsonDumpsIndentStr = json.dumps(info, indent=1)
        f = open(setting.UPGRADE_INFO, 'w')
        f.write(jsonDumpsIndentStr)
        f.close()

        time.sleep(5)
        # os.system("reboot")





